package com.tangding.controller;

import java.util.ArrayList;
import java.util.List;

import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.tangding.common.exception.GException;
import com.tangding.pojo.request.role.CreateParams;
import com.tangding.pojo.request.role.UpdateParams;
import com.tangding.pojo.response.MessageDto;
import com.tangding.service.entity.role.Role;
import com.tangding.service.role.RoleService;

/**
 * @description 
 *
 * @author Ranger
 * @version 2017年11月9日_下午7:00:01
 *
 */
@RestController
@RequestMapping("/role")
@RequiresAuthentication
public class RoleController {
	
	@Autowired
	RoleService roleService;
	
	@RequestMapping(value = {"/list"}, method = RequestMethod.GET)
	@RequiresPermissions(value = {"role_list", "role_delete", "role_update", "role_create"}, logical = Logical.OR)
	public MessageDto list() throws GException {
		
		return MessageDto.responseSuccess(roleService.list());
	}
	
	@RequestMapping(value = {"/delete"}, method = RequestMethod.POST)
	@RequiresPermissions(value = {"role_delete"})
	public MessageDto delete(int roleId) throws GException {
		roleService.delete(roleId);
		return MessageDto.responseSuccess();
	}
	
	@RequestMapping(value = {"/create"}, method = RequestMethod.POST)
	@RequiresPermissions(value = {"role_create"})
	public MessageDto create(CreateParams params) throws GException {
		Role role = new Role();
		role.setRoleDesc(params.getRoleDesc());
		role.setRoleName(params.getRoleName());
		
		String permissionStr = params.getPermission().trim();
		String[] permissions = permissionStr.split("[,]");
		List<String> permissionList = new ArrayList<>();
		for (String permission : permissions) {
			permissionList.add(permission);
		}
		role.setPermission(permissionList);
		roleService.add(role);
		return MessageDto.responseSuccess();
	}
	
	@RequestMapping(value = {"/update"}, method = RequestMethod.POST)
	@RequiresPermissions(value = {"role_update"})
	public MessageDto update(UpdateParams params) throws GException {
		Role role = new Role();
		role.setRoleId(params.getRoleId());
		role.setRoleDesc(params.getRoleDesc());
		role.setRoleName(params.getRoleName());
		
		String permissionStr = params.getPermission().trim();
		String[] permissions = permissionStr.split("[,]");
		List<String> permissionList = new ArrayList<>();
		for (String permission : permissions) {
			permissionList.add(permission);
		}
		role.setPermission(permissionList);
		
		roleService.update(role);
		return MessageDto.responseSuccess();
	}
}
